<?php

namespace App\Exceptions;

use App\Enums\ResponseCode;
use App\Traits\ApiResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    use ApiResponse;
    /**
     * A list of the exception types that are not reported.
     * 属性定义了不会被记录到日志的异常
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        BusinessException::class,
        ApiExceptions::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * render方法会将异常信息渲染到HTTP响应中
     * @param $request
     * @param Throwable $e
     * @return Response|JsonResponse|\Symfony\Component\HttpFoundation\Response
     * @throws BusinessException
     * @throws Throwable
     */
    public function render($request, Throwable $e)
    {
        //拦截API请求的异常
        if($request->is('api/*')) {
            // 请求类型错误异常抛出
            if ($e instanceof MethodNotAllowedHttpException) {
                return $this->error(trans("exception.没有找到请求"),ResponseCode::METHOD_NOT_ALLOWED);
            } elseif ($e instanceof ThrottleRequestsException) {
                return $this->error(trans("exception.您的请求太快了请稍后重试"),ResponseCode::TOO_MANY_REQUESTS);
            } elseif ($e instanceof ValidationException) {
                // 参数校验错误异常抛出
                return $this->fail( trans(array_values($e->errors())[0][0]),ResponseCode::VALIDATION_ERROR);
//                return $this->fail( trans("exception.数据验证失败"),ResponseCode::VALIDATION_ERROR);
            } elseif ($e instanceof NotFoundHttpException) {
                // 路由不存在异常抛出
                return $this->error(trans("exception.没有找到该页面"),ResponseCode::NOT_FOUND);
            } elseif ($e instanceof AuthenticationException) {
                $requestMessage = [
                    'url' => $request->path(),
                  'ip'=>$request->getClientIp(),
                    'token'=>$request->header('Authorization'),
                ];
                Log::info("登录失败：", $requestMessage);
                return $this->error('未登录请重新登录',ResponseCode::UNAUTHORIZED);
            }elseif ($e instanceof JWTException) {
                // JWT异常抛出
                return $this->error('未登录请重新登录',ResponseCode::UNAUTHORIZED);
            } else if ($e instanceof ApiExceptions) {
                return self::error($e->getMessage(),$e->getCode());
            } elseif ($e instanceof BusinessException){
                // 自定义错误异常抛出
                if(config('app.debug')){
                    return response()->json([
                        'status' => 'error',
                        'code' => $e->getCode(),
                        'local' => App::getLocale(),
                        'message' => $e->getMessage(),
                        'data' => new \stdClass(),
                        'error' => $e->__toArray()
                    ]);
                }else{
                    return response()->json([
                        'status' => 'error',
                        'code' => $e->getCode(),
                        'local' => App::getLocale(),
                        'message' => $e->getMessage(),
                        'data' => new \stdClass(),
                        'error' => new \stdClass(),
                    ]);
                }

            }
        }
        return parent::render($request, $e);
    }
}
